<template>
  <div class="login">
    <!-- 关闭按钮 -->
    <div class="close">
      <span class="iconfont iconicon-test"></span>
    </div>
    <!-- new logo图标 -->
    <div class="logo">
      <span class="iconfont iconnew"></span>
    </div>
    <!-- 输入框（2个） -->
    <div class="inputs">
      <myipt
        type="text"
        placeholder="请输入手机号/用户名"
        v-model="user.username"
        :rules="/^1[35789]\d{9}$|^1\d{4}$/"
        msg="手机号输入不合法"
      ></myipt>
      <myipt
        type="password"
        placeholder="请输入密码"
        v-model="user.password"
        :rules="/^\S{3,16}$/"
        msg="请输入3-16位的密码"
        @keyup.enter.native="login"
      ></myipt>
      <!-- native可以在子组件上添加父组件的事件，并在父组件触发 -->
    </div>
    <!-- 提示注册 -->
    <p class="tips">
      没有账号？
      <a href="#/register">去注册</a>
    </p>
    <!-- 登录按钮 -->
    <mybtn class="iconfont iconweixin" @click="login">登录</mybtn>
  </div>
</template>

<script>
import mybtn from "@/components/mybtn";
import myipt from "@/components/myipt";
import { login } from "@/apis/users.js";
export default {
  components: {
    myipt,
    mybtn,
  },
  data() {
    return {
      user: {
        username: "10088",
        password: "000",
      },
    };
  },
  methods: {
    // 传送参数，用axios发送请求
    // 标记当前方法是异步方法
    // async与await搭配，能以同步方式调用异步方法
    async login() {
      console.log(this.user);
      let res = await login(this.user);
      console.log(res);
      if (res.data.statusCode === 401) {
        this.$toast.fail({
          message: "用户名或密码输入错误",
          duration: 2000,
        });
      } else {
        this.$toast.success("登录成功");
        // 将token进行本地存储
        localStorage.setItem("news", res.data.data.token);
        // 再将用户信息存储在本地,user本来是对象，转换成字符串存储
        localStorage.setItem("news2", JSON.stringify(res.data.data.user));
        // $router实现路由跳转
        // this.$router.push({
        //   path: "/personal/" + res.data.data.user.id,
        // });

        // 获取可能传递的回传url
        // decodeURIComponent:可以对url进行解码
        let backUrl = decodeURIComponent(window.location.hash.split("=")[1]);
        console.log(backUrl);
        if (backUrl && backUrl != "undefined") {
          // 跳到相应文章详情页
          this.$router.push({
            path: backUrl,
          });
        } else {
          // 返回新闻首页
          this.$router.push({
            path: "/personal/" + res.data.data.user.id,
          });
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.login {
  padding: 20 * 100vw/360;
  .close {
    font-size: 20 * 100vw/360;
  }
  .logo {
    display: flex;
    justify-content: center;
    span {
      font-size: 126 * 100vw/360;
      color: #d81e06;
    }
  }
  .inputs {
    margin-top: 20 * 100vw/360;
    .myipt {
      margin-bottom: 20 * 100vw/360;
    }
  }
  .mybtn {
    margin-top: 30 * 100vw/360;
  }
}
</style>